<!-- 商户开通服务 -->
<template>
  <div>
    <a-modal title="开通" :width="1200" :open="openForm" @cancel="onClose" :maskClosable="false" :destroyOnClose="true">
      <a-form ref="formRef" :model="formData" :rules="rules" layout="top">
        <a-row>
          <a-form-item label="开通服务类型" name="serviceType">
            <a-checkbox-group v-model:value="formData.serviceType" :options="SERVICE_TYPE_LIST" @change="changeServiceType" />
          </a-form-item>
        </a-row>
        <a-row v-if="formData.serviceType.includes(1)">
          <a-col :span="24" class="py-2">
            <a-flex justify="space-between">
              <group-title :iconOptions="{ class: 'text-blue-500' }">代收</group-title>
              <a-button type="primary" @click="addRow('collectionList')">添加</a-button>
            </a-flex>
          </a-col>
          <a-col :span="24">
            <a-table
              :dataSource="formData.collectionList"
              :columns="columns.filter((item) => item.dataIndex != 'serviceType')"
              :pagination="false"
              bordered
              size="small"
            >
              <template #bodyCell="bodyCell">
                <template v-if="bodyCell.column.dataIndex === 'channelName'">
                  <div v-if="!bodyCell.record.isAdd">{{ bodyCell.text }}</div>
                  <a-form-item v-else :rules="bodyCell.column.rules(bodyCell)" :name="['collectionList', bodyCell.index, 'channelName']">
                    <CustomSelect
                      v-model:value="bodyCell.record[bodyCell.column.dataIndex]"
                      :placeholder="'请先选择支付通道'"
                      @change="(...data) => changeChannel(data, bodyCell)"
                      :api="channelApi.queryPage"
                      :queryParams="{
                        billType: [0],
                      }"
                      value-field="channelName"
                      label-field="channelName"
                    />
                  </a-form-item>
                </template>
                <template v-if="bodyCell.column.dataIndex === 'onlineRate'">
                  <a-form-item :rules="bodyCell.column.rules(bodyCell)" :name="['collectionList', bodyCell.index, 'onlineRate']">
                    <a-input v-model:value="formData.collectionList[bodyCell.index][bodyCell.column.dataIndex]" placeholder="请输入线上服务费" />
                  </a-form-item>
                </template>
                <template v-if="bodyCell.column.dataIndex === 'offlineRate'">
                  <a-form-item :rules="bodyCell.column.rules(bodyCell)" :name="['collectionList', bodyCell.index, 'offlineRate']">
                    <a-input v-model:value="formData.collectionList[bodyCell.index][bodyCell.column.dataIndex]" placeholder="请输入线下服务费" />
                  </a-form-item>
                </template>
                <template v-if="bodyCell.column.dataIndex === 'action'">
                  <div class="smart-table-operate">
                    <a-button v-if="bodyCell.record.isAdd" type="primary" @click="delRow('collectionList', bodyCell)"><DeleteOutlined /></a-button>
                  </div>
                </template>
              </template> </a-table
          ></a-col>
        </a-row>
        <a-row v-if="formData.serviceType.includes(2)">
          <a-col :span="24" class="py-2">
            <a-flex justify="space-between">
              <group-title :iconOptions="{ class: 'text-blue-500' }">代付</group-title>
              <a-button type="primary" @click="addRow('paymentList')">添加</a-button>
            </a-flex>
          </a-col>
          <a-col :span="24">
            <a-table
              :dataSource="formData.paymentList"
              :columns="columns.filter((item) => item.dataIndex != 'serviceType')"
              :pagination="false"
              bordered
              size="small"
            >
              <template #bodyCell="bodyCell">
                <template v-if="bodyCell.column.dataIndex === 'channelName'">
                  <div v-if="!bodyCell.record.isAdd">{{ bodyCell.text }}</div>
                  <a-form-item v-else :rules="bodyCell.column.rules(bodyCell)" :name="['paymentList', bodyCell.index, 'channelName']">
                    <CustomSelect
                      v-model:value="bodyCell.record[bodyCell.column.dataIndex]"
                      :placeholder="'请先选择支付通道'"
                      @change="(...data) => changeChannel(data, bodyCell)"
                      :api="channelApi.queryPage"
                      :queryParams="{
                        billType: [1],
                      }"
                      value-field="channelName"
                      label-field="channelName"
                    />
                  </a-form-item>
                </template>
                <template v-if="bodyCell.column.dataIndex === 'onlineRate'">
                  <a-form-item :rules="bodyCell.column.rules(bodyCell)" :name="['paymentList', bodyCell.index, 'onlineRate']">
                    <a-input v-model:value="formData.paymentList[bodyCell.index][bodyCell.column.dataIndex]" placeholder="请输入线上服务费" />
                  </a-form-item>
                </template>
                <template v-if="bodyCell.column.dataIndex === 'offlineRate'">
                  <a-form-item :rules="bodyCell.column.rules(bodyCell)" :name="['paymentList', bodyCell.index, 'offlineRate']">
                    <a-input v-model:value="formData.paymentList[bodyCell.index][bodyCell.column.dataIndex]" placeholder="请输入线下服务费" />
                  </a-form-item>
                </template>
                <template v-if="bodyCell.column.dataIndex === 'action'">
                  <div class="smart-table-operate">
                    <a-button v-if="bodyCell.record.isAdd" type="primary" @click="delRow('paymentList', bodyCell)"><DeleteOutlined /></a-button>
                  </div>
                </template>
              </template> </a-table
          ></a-col>
        </a-row>
        <a-row v-if="formData.serviceType.includes(3)">
          <a-col :span="24" class="py-2">
            <a-flex justify="space-between">
              <group-title :iconOptions="{ class: 'text-blue-500' }">分账</group-title>
              <a-button type="primary" @click="addRow('autoSplitList')">添加</a-button>
            </a-flex>
          </a-col>
          <a-col :span="24">
            <a-table :dataSource="formData.autoSplitList" :columns="columns" :pagination="false" bordered size="small">
              <template #bodyCell="bodyCell">
                <template v-if="bodyCell.column.dataIndex === 'channelName'">
                  <div v-if="!bodyCell.record.isAdd">{{ bodyCell.text }}</div>
                  <a-form-item v-else :rules="bodyCell.column.rules(bodyCell)" :name="['autoSplitList', bodyCell.index, 'channelName']">
                    <CustomSelect
                      v-model:value="bodyCell.record[bodyCell.column.dataIndex]"
                      :placeholder="'请先选择支付通道'"
                      @change="(...data) => changeChannel(data, bodyCell)"
                      :api="channelApi.queryPage"
                      :queryParams="{
                        billType: [2],
                      }"
                      value-field="channelName"
                      label-field="channelName"
                    />
                  </a-form-item>
                </template>
                <template v-if="bodyCell.column.dataIndex === 'serviceType'">
                  <a-form-item :rules="bodyCell.column.rules(bodyCell)" :name="['autoSplitList', bodyCell.index, 'serviceType']">
                    <a-select
                      placeholder="请选择服务类型"
                      v-model:value="formData.autoSplitList[bodyCell.index][bodyCell.column.dataIndex]"
                      :options="SERVICE_TYPE.filter((pro) => pro.value == 3 || pro.value == 4)"
                    />
                  </a-form-item>
                </template>
                <template v-if="bodyCell.column.dataIndex === 'onlineRate'">
                  <a-form-item :rules="bodyCell.column.rules(bodyCell)" :name="['autoSplitList', bodyCell.index, 'onlineRate']">
                    <a-input v-model:value="formData.autoSplitList[bodyCell.index][bodyCell.column.dataIndex]" placeholder="请输入线上服务费" />
                  </a-form-item>
                </template>
                <template v-if="bodyCell.column.dataIndex === 'offlineRate'">
                  <a-form-item :rules="bodyCell.column.rules(bodyCell)" :name="['autoSplitList', bodyCell.index, 'offlineRate']">
                    <a-input v-model:value="formData.autoSplitList[bodyCell.index][bodyCell.column.dataIndex]" placeholder="请输入线下服务费" />
                  </a-form-item>
                </template>
                <template v-if="bodyCell.column.dataIndex === 'action'">
                  <div class="smart-table-operate">
                    <a-button v-if="bodyCell.record.isAdd" type="primary" @click="delRow('autoSplitList', bodyCell)"><DeleteOutlined /></a-button>
                  </div>
                </template>
              </template> </a-table
          ></a-col>
        </a-row>
      </a-form>
      <template #footer>
        <a-space>
          <a-button @click="onUpdataClose">取消</a-button>
          <a-button type="primary" @click="onSubmit">保存</a-button>
        </a-space>
      </template>
    </a-modal>
  </div>
</template>
<script setup>
  import { nextTick, reactive, ref, computed, watch, h } from 'vue'
  import { SmartLoading } from '/src/components/framework/smart-loading'
  import { message } from 'ant-design-vue'
  import { merchantApi } from '/src/api/business/b-operation/merchant/merchant-api'
  import { channelApi } from '/@/api/business/b-operation/channel/channel-api'
  import dayjs from 'dayjs'
  import { cloneDeep } from 'lodash-es'
  import CustomSelect from '/@/components/business/comment/CustomSelect.vue'
  import { selectDictLabel } from '/@/utils/common'
  import { costRate } from '/@/utils/validate'
  import {
    SERVICE_TYPE, // 开通服务
  } from '/@/constants/dict'

  const SERVICE_TYPE_LIST = []
  for (let item of SERVICE_TYPE) {
    let val = item.value == '3' || item.value == '4' ? 3 : item.value
    let label = item.value == '3' || item.value == '4' ? '分账' : item.label
    if (item.value != 4) {
      SERVICE_TYPE_LIST.push({
        label: label,
        desc: val,
        value: val,
      })
    }
  }

  const props = defineProps({
    open: {
      type: Boolean,
      default: false,
    },
    rowData: {
      type: Object,
      default: () => {},
    },
  })
  // ------------------------ 事件 ------------------------

  const emit = defineEmits(['update:open', 'ok'])
  const openForm = computed({ get: () => props.open, set: (val) => emit('update:open', val) })

  // ------------------------ 显示与隐藏 ------------------------

  // 获取表单信息
  const formRef = ref()
  async function getFormData(data) {
    SmartLoading.show()
    let res = await merchantApi.getServiceList(data)
    if (res.code === 200) {
      formData.value = res.data
      formData.value.merchantId = data.id
      formData.value.serviceType = []
      formData.value.serviceTypeSet.forEach((element) => {
        if (element == 3 || element == 4) {
          formData.value.serviceType.push(3)
        } else {
          formData.value.serviceType.push(element)
        }
      })
      console.log(formData.value)
    }
    SmartLoading.hide()
  }
  async function show(rowData) {
    let params = { id: rowData.id }
    await getFormData(params)
    nextTick(() => {
      formRef.value.clearValidate()
    })
  }

  function onClose() {
    formData.value = { ...cloneDeep(initForm) }
    openForm.value = false
  }

  const columns = ref([
    {
      title: '支付通道',
      dataIndex: 'channelName',
      rules: (bodyCell) => {
        return [
          {
            required: true,
            message: `${bodyCell.column.title} 必填`,
          },
        ]
      },
    },
    {
      title: '分账类型',
      dataIndex: 'serviceType',
      customRender: ({ text }) => {
        return selectDictLabel(SERVICE_TYPE, text)
      },
      rules: (bodyCell) => {
        return [
          {
            required: true,
            message: `${bodyCell.column.title} 必填`,
          },
        ]
      },
    },
    {
      title: '线上成本价（%）',
      dataIndex: 'costOnlineRate',
    },
    {
      title: '线下成本价（%）',
      dataIndex: 'costOfflineRate',
    },
    {
      title: '线上服务费（%）',
      dataIndex: 'onlineRate',
      rules: (bodyCell) => {
        return [
          {
            required: true,
            message: `${bodyCell.column.title} 必填`,
          },
          {
            validator: (rule, value, callback) => costRate(rule, value, callback, bodyCell.record.costOnlineRate),
          },
        ]
      },
    },
    {
      title: '线下服务费（%）',
      dataIndex: 'offlineRate',
      rules: (bodyCell) => {
        return [
          {
            required: true,
            message: `${bodyCell.column.title} 必填`,
          },
          {
            validator: (rule, value, callback) => costRate(rule, value, callback, bodyCell.record.costOfflineRate),
          },
        ]
      },
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 70,
    },
  ])

  /* 修改弹窗 */
  const initForm = {
    merchantId: undefined,
    serviceType: [], //开通服务
    paymentList: [], //代付
    autoSplitList: [], //分账
    collectionList: [
      {
        channelId: undefined, //通道ID
        serviceType: undefined, //服务类型
        channelName: undefined, //通道名称
        channelType: undefined, //通道类型
        costOnlineRate: undefined, //线上成本价
        costOfflineRate: undefined, //线下成本价
        onlineRate: undefined, //线上服务费
        offlineRate: undefined, //线下服务费
      },
    ], //代收
  }
  const formData = ref({ ...cloneDeep(initForm) })
  const rules = {
    serviceType: [{ required: true, message: '开通服务 必填' }],
    // channelName: [{ required: true, message: '支付通道 必填' }],
    // onlineRate: [{ required: true, message: '线下服务费 必填' }],
    // offlineRate: [{ required: true, message: '线下服务费 必填' }],
  }
  const visibleUpdata = ref(false)
  function onUpdataClose() {
    visibleUpdata.value = false
  }

  // 开通服务切换时
  const changeServiceType = (e) => {
    console.log(e)
  }

  // 表单校验
  const validateForm = async () => {
    let isValid = false
    try {
      await formRef.value.validate()
      isValid = true
    } catch (error) {
      message.warning(error.errorFields[0].errors)
      isValid = false
    }
    return isValid
  }
  // 点击确定，验证表单
  async function onSubmit() {
    console.log(formData.value)

    validateForm().then((isValid) => {
      if (isValid) {
        merchantApi.serviceSave(formData.value).then((res) => {
          if (res.code === 200) {
            message.success('保存成功')
            onClose()
            emit('ok')
          }
        })
        console.log('')
      }
    })
  }

  /* 修改弹窗 */

  /* 列表操作 */

  const addRow = (field) => {
    const myMap = {
      collectionList: 1,
      paymentList: 2,
      autoSplitList: 3,
    }
    formData.value[field].push({ isAdd: true, serviceType: myMap[field] })
  }
  const delRow = (field, row) => {
    const { index, record } = row
    if (record.isAdd) {
      formData.value[field].splice(index, 1)
    }
  }
  const changeChannel = (options, bodyCell) => {
    let { id, dCostOnlineRate, dCostOfflineRate } = options[1][0]
    bodyCell.record.channelId = id ? id : ''
    bodyCell.record.costOnlineRate = dCostOnlineRate ? dCostOnlineRate : ''
    bodyCell.record.costOfflineRate = dCostOfflineRate ? dCostOfflineRate : ''
    bodyCell.record.onlineRate = ''
    bodyCell.record.offlineRate = ''
  }

  /* 列表操作 */

  defineExpose({
    show,
  })
  watch(
    [() => props.rowData, () => props.open],
    (val) => {
      if (props.open && props.rowData) {
        show(val[0])
      }
    },
    { immediate: true },
  )
</script>
